package com.cskaoyan.controller.admin;

import com.cskaoyan.bean.BaseRespVo;

import com.cskaoyan.bean.admin.other.AdminLoginInfoVo;
import com.cskaoyan.bean.admin.other.DashBoardVo;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.service.admin.AdminService;
import com.cskaoyan.util.Md5utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cskaoyan.bean.admin.other.InfoDataVo;
import com.cskaoyan.bean.admin.other.LoginUserBo;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admin")
public class AuthController {

    @Autowired
    AdminService adminService;

    @PostMapping("auth/login")
    public BaseRespVo login(@RequestBody LoginUserBo loginUserBo){

//        UsernamePasswordToken token = new UsernamePasswordToken(loginUserBo.getUsername(), loginUserBo.getPassword());
        String type = "admin";
        String password = Md5utils.getMd5Result(loginUserBo.getPassword());
        MallToken token = new MallToken(loginUserBo.getUsername(), password , type);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("用户名或密码不正确");
        }
        Session session = subject.getSession();
        return BaseRespVo.ok(session.getId());
    }

    @GetMapping("auth/info")
    public BaseRespVo info(String token, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        AdminLoginInfoVo loginInfoVo = adminService.selectInfo(username,ip);
        return BaseRespVo.ok(loginInfoVo);
    }

    @GetMapping("dashboard")
    public BaseRespVo dashBoard(){

        DashBoardVo dashBoardVo = adminService.queryCount();
        return BaseRespVo.ok(dashBoardVo);
    }

    @RequestMapping("auth/logout")
    public BaseRespVo logout(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return BaseRespVo.ok();
    }
}
